<template>
  <div class="table-form-designer">
    <div class="designer-container">
      <!-- 左侧组件面板 -->
      <div class="component-panel">
        <div class="panel-header">
          <h3>表单组件</h3>
        </div>
        <div class="component-list">
          <div class="component-group">
            <h4>基础组件</h4>
            <div class="component-items">
              <div
                v-for="component in basicComponents"
                :key="component.type"
                class="component-item"
                draggable="true"
                @dragstart="handleDragStart($event, component)"
              >
                <el-icon class="component-icon">
                  <component :is="component.icon" />
                </el-icon>
                <span class="component-name">{{ component.name }}</span>
              </div>
            </div>
          </div>

          <div class="component-group">
            <h4>选择组件</h4>
            <div class="component-items">
              <div
                v-for="component in selectComponents"
                :key="component.type"
                class="component-item"
                draggable="true"
                @dragstart="handleDragStart($event, component)"
              >
                <el-icon class="component-icon">
                  <component :is="component.icon" />
                </el-icon>
                <span class="component-name">{{ component.name }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间设计区域 -->
      <div class="design-area">
        <div class="design-header">
          <h3>表单设计</h3>
          <div class="design-actions">
            <el-button size="small" @click="handlePreview">
              <el-icon><View /></el-icon>
              预览
            </el-button>
            <el-button size="small" @click="handleSave">
              <el-icon><Document /></el-icon>
              保存配置
            </el-button>
            <el-button size="small" @click="handleClear">
              <el-icon><Delete /></el-icon>
              清空
            </el-button>
          </div>
        </div>

        <div class="form-canvas" @drop="handleDrop" @dragover="handleDragOver">
          <div v-if="formFields.length === 0" class="empty-canvas">
            <el-icon class="empty-icon"><Plus /></el-icon>
            <p>拖拽左侧组件到此处开始设计表单</p>
          </div>

          <div v-else class="form-builder">
            <el-form label-width="120px" size="large">
              <draggable
                v-model="formFields"
                group="form-fields"
                item-key="id"
                class="form-fields-list"
              >
                <template #item="{ element, index }">
                  <div
                    class="form-field-wrapper"
                    :class="{ active: selectedFieldIndex === index }"
                    @click="selectField(index)"
                  >
                    <el-form-item :label="element.label" :required="element.required">
                      <component
                        :is="getFieldComponent(element.type)"
                        v-bind="getFieldProps(element)"
                        :placeholder="element.placeholder"
                        :disabled="true"
                      />
                    </el-form-item>

                    <div class="field-actions">
                      <el-button size="small" type="primary" text @click.stop="selectField(index)">
                        <el-icon><Edit /></el-icon>
                      </el-button>
                      <el-button size="small" type="danger" text @click.stop="removeField(index)">
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                  </div>
                </template>
              </draggable>
            </el-form>
          </div>
        </div>
      </div>

      <!-- 右侧属性面板 -->
      <div class="property-panel">
        <div class="panel-header">
          <h3>属性配置</h3>
        </div>

        <div v-if="selectedField" class="property-form">
          <el-form label-width="80px" size="small">
            <el-form-item label="字段名称">
              <el-input
                v-model="selectedField.name"
                placeholder="字段名称"
                @input="syncFormConfig"
              />
            </el-form-item>

            <el-form-item label="字段标签">
              <el-input
                v-model="selectedField.label"
                placeholder="字段标签"
                @input="syncFormConfig"
              />
            </el-form-item>

            <el-form-item label="占位符">
              <el-input
                v-model="selectedField.placeholder"
                placeholder="占位符文本"
                @input="syncFormConfig"
              />
            </el-form-item>

            <el-form-item label="是否必填">
              <el-switch v-model="selectedField.required" @change="syncFormConfig" />
            </el-form-item>

            <!-- 表格显示配置 -->
            <el-form-item label="表格显示">
              <el-switch v-model="selectedField.showInTable" @change="syncFormConfig" />
            </el-form-item>

            <el-form-item label="表格宽度" v-if="selectedField.showInTable">
              <el-input-number
                v-model="selectedField.tableWidth"
                :min="50"
                :max="1000"
                :step="10"
                placeholder="表格列宽度(px)"
                @change="syncFormConfig"
              />
            </el-form-item>

            <el-form-item label="默认值" v-if="showDefaultValue">
              <el-input
                v-model="selectedField.defaultValue"
                placeholder="默认值"
                @input="syncFormConfig"
              />
            </el-form-item>

            <!-- 选择类型组件的选项配置 -->
            <div v-if="isSelectType(selectedField.type)">
              <el-form-item label="选项来源">
                <el-radio-group v-model="selectedField.optionSource" @change="handleOptionSourceChange">
                  <el-radio label="manual">手动配置</el-radio>
                  <el-radio label="api">API获取</el-radio>
                </el-radio-group>
              </el-form-item>

              <!-- 手动配置选项 -->
              <el-form-item label="选项配置" v-if="selectedField.optionSource === 'manual'">
                <div class="options-config">
                  <div
                    v-for="(option, index) in selectedField.options"
                    :key="index"
                    class="option-item"
                  >
                    <el-input
                      v-model="option.label"
                      placeholder="选项标签"
                      size="small"
                      @input="syncFormConfig"
                    />
                    <el-input
                      v-model="option.value"
                      placeholder="选项值"
                      size="small"
                      @input="syncFormConfig"
                    />
                    <el-button size="small" type="danger" text @click="removeOption(index)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                  <el-button size="small" type="primary" text @click="addOption">
                    <el-icon><Plus /></el-icon>
                    添加选项
                  </el-button>
                </div>
              </el-form-item>

              <!-- API配置选项 -->
              <div v-if="selectedField.optionSource === 'api'">
                <el-form-item label="API地址">
                  <el-input
                    v-model="selectedField.apiUrl"
                    placeholder="API接口地址"
                    @input="syncFormConfig"
                  />
                </el-form-item>
                <el-form-item label="请求方法">
                  <el-select v-model="selectedField.apiMethod" @change="syncFormConfig">
                    <el-option label="GET" value="get" />
                    <el-option label="POST" value="post" />
                  </el-select>
                </el-form-item>
                <el-form-item label="数据路径">
                  <el-input
                    v-model="selectedField.apiDataPath"
                    placeholder="如：data.list"
                    @input="syncFormConfig"
                  />
                </el-form-item>
                <el-form-item label="标签字段">
                  <el-input
                    v-model="selectedField.apiLabelField"
                    placeholder="如：name"
                    @input="syncFormConfig"
                  />
                </el-form-item>
                <el-form-item label="值字段">
                  <el-input
                    v-model="selectedField.apiValueField"
                    placeholder="如：id"
                    @input="syncFormConfig"
                  />
                </el-form-item>
                <el-button size="small" @click="testApiOptions">测试API</el-button>
              </div>
            </div>
          </el-form>
        </div>

        <div v-else class="no-selection">
          <el-icon class="no-selection-icon"><InfoFilled /></el-icon>
          <p>请选择一个表单字段进行配置</p>
        </div>
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="表单预览"
      width="800px"
      :before-close="handleClosePreview"
    >
      <FormPreview :fields="formFields" />
    </el-dialog>

    <!-- 保存配置对话框 -->
    <el-dialog
      v-model="saveVisible"
      title="保存表格配置"
      width="500px"
    >
      <el-form :model="saveForm" label-width="100px">
        <el-form-item label="配置名称" required>
          <el-input v-model="saveForm.name" placeholder="请输入配置名称" />
        </el-form-item>
        <el-form-item label="配置描述">
          <el-input v-model="saveForm.description" type="textarea" placeholder="请输入配置描述" />
        </el-form-item>
        <el-form-item label="数据权限">
          <el-switch v-model="saveForm.dataPermission" />
          <span class="ml-2 text-sm text-gray-500">启用后可对具体数据行进行权限控制</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="saveVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  View,
  Delete,
  Plus,
  Edit,
  InfoFilled,
  Document,
  EditPen,
  Select,
  Calendar,
  Upload
} from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import FormPreview from '/@/components/FormDesigner/FormPreview.vue'
import { FormField, FieldType, Option } from '/@/components/FormDesigner/types'
import request from '/@/utils/request'

interface ComponentConfig {
  type: FieldType
  name: string
  icon: any
  defaultProps?: Record<string, any>
}

interface SaveForm {
  name: string
  description: string
  dataPermission: boolean
}

const props = defineProps<{
  modelValue?: FormField[]
  configName?: string
}>()

const emit = defineEmits<{
  'update:modelValue': [value: FormField[]]
  'save': [config: any]
}>()

// 基础组件配置
const basicComponents: ComponentConfig[] = [
  { type: FieldType.TEXT, name: '单行文本', icon: EditPen },
  { type: FieldType.TEXTAREA, name: '多行文本', icon: EditPen },
  { type: FieldType.NUMBER, name: '数字', icon: EditPen },
  { type: FieldType.DATE, name: '日期', icon: Calendar },
  { type: FieldType.DATETIME, name: '日期时间', icon: Calendar },
  { type: FieldType.FILE, name: '文件上传', icon: Upload }
]

// 选择组件配置
const selectComponents: ComponentConfig[] = [
  { type: FieldType.SELECT, name: '下拉选择', icon: Select },
  { type: FieldType.RADIO, name: '单选框', icon: Select },
  { type: FieldType.CHECKBOX, name: '多选框', icon: Select }
]

// 表单字段列表
const formFields = ref<FormField[]>(Array.isArray(props.modelValue) ? props.modelValue : [])
const selectedFieldIndex = ref<number>(-1)
const previewVisible = ref(false)
const saveVisible = ref(false)

// 保存表单
const saveForm = reactive<SaveForm>({
  name: props.configName || '',
  description: '',
  dataPermission: false
})

// 计算属性
const selectedField = computed(() => {
  return selectedFieldIndex.value >= 0 ? formFields.value[selectedFieldIndex.value] : null
})

const showDefaultValue = computed(() => {
  if (!selectedField.value) return false
  return !isSelectType(selectedField.value.type)
})

const formConfig = computed(() => {
  return {
    fields: formFields.value,
    layout: {
      columns: 1,
      labelWidth: '120px',
      size: 'default'
    },
    validation: {
      rules: {}
    }
  }
})

// 方法
const generateId = () => {
  return 'field_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
}

const handleDragStart = (event: DragEvent, component: ComponentConfig) => {
  if (event.dataTransfer) {
    event.dataTransfer.setData('text/plain', JSON.stringify(component))
  }
}

const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
}

const handleDrop = (event: DragEvent) => {
  event.preventDefault()
  const componentData = event.dataTransfer?.getData('text/plain')
  if (componentData) {
    const component: ComponentConfig = JSON.parse(componentData)
    addField(component)
  }
}

const addField = (component: ComponentConfig) => {
  const newField: FormField = {
    id: generateId(),
    type: component.type,
    label: component.name,
    name: `field_${formFields.value.length + 1}`,
    required: false,
    showInTable: true,
    tableWidth: 120,
    optionSource: 'manual',
    options: isSelectType(component.type) ? [{ label: '选项1', value: 'option1' }] : undefined,
    apiUrl: '',
    apiMethod: 'get',
    apiDataPath: 'data',
    apiLabelField: 'label',
    apiValueField: 'value'
  }
  formFields.value.push(newField)
  syncFormConfig()
}

const selectField = (index: number) => {
  selectedFieldIndex.value = index
}

const removeField = (index: number) => {
  formFields.value.splice(index, 1)
  if (selectedFieldIndex.value === index) {
    selectedFieldIndex.value = -1
  } else if (selectedFieldIndex.value > index) {
    selectedFieldIndex.value--
  }
  syncFormConfig()
}

const isSelectType = (type: FieldType) => {
  return [FieldType.SELECT, FieldType.RADIO, FieldType.CHECKBOX].includes(type)
}

const addOption = () => {
  if (selectedField.value && selectedField.value.options) {
    selectedField.value.options.push({
      label: `选项${selectedField.value.options.length + 1}`,
      value: `option${selectedField.value.options.length + 1}`
    })
    syncFormConfig()
  }
}

const removeOption = (index: number) => {
  if (selectedField.value && selectedField.value.options) {
    selectedField.value.options.splice(index, 1)
    syncFormConfig()
  }
}

const handleOptionSourceChange = () => {
  if (selectedField.value) {
    if (selectedField.value.optionSource === 'api') {
      selectedField.value.options = []
    } else {
      selectedField.value.options = [{ label: '选项1', value: 'option1' }]
    }
    syncFormConfig()
  }
}

const testApiOptions = async () => {
  if (!selectedField.value || !selectedField.value.apiUrl) {
    ElMessage.warning('请先配置API地址')
    return
  }

  try {
    const response = await request({
      url: selectedField.value.apiUrl,
      method: selectedField.value.apiMethod || 'get'
    })

    // 根据配置的数据路径获取数据
    let data = response
    if (selectedField.value.apiDataPath) {
      const paths = selectedField.value.apiDataPath.split('.')
      for (const path of paths) {
        data = data[path]
      }
    }

    if (Array.isArray(data)) {
      const options = data.map((item: any) => ({
        label: item[selectedField.value!.apiLabelField || 'label'],
        value: item[selectedField.value!.apiValueField || 'value']
      }))
      selectedField.value.options = options
      syncFormConfig()
      ElMessage.success('API测试成功，已获取选项数据')
    } else {
      ElMessage.error('API返回数据格式不正确，应为数组格式')
    }
  } catch (error) {
    ElMessage.error('API测试失败：' + error)
  }
}

const getFieldComponent = (type: FieldType) => {
  const componentMap = {
    [FieldType.TEXT]: 'el-input',
    [FieldType.TEXTAREA]: 'el-input',
    [FieldType.NUMBER]: 'el-input-number',
    [FieldType.SELECT]: 'el-select',
    [FieldType.RADIO]: 'el-radio-group',
    [FieldType.CHECKBOX]: 'el-checkbox-group',
    [FieldType.DATE]: 'el-date-picker',
    [FieldType.DATETIME]: 'el-date-picker',
    [FieldType.FILE]: 'el-upload'
  }
  return componentMap[type] || 'el-input'
}

const getFieldProps = (field: FormField) => {
  const baseProps: Record<string, any> = {}
  
  switch (field.type) {
    case FieldType.TEXTAREA:
      baseProps.type = 'textarea'
      break
    case FieldType.DATE:
      baseProps.type = 'date'
      break
    case FieldType.DATETIME:
      baseProps.type = 'datetime'
      break
  }
  
  return baseProps
}

const syncFormConfig = () => {
  emit('update:modelValue', formFields.value)
}

const handlePreview = () => {
  previewVisible.value = true
}

const handleClosePreview = () => {
  previewVisible.value = false
}

const handleSave = () => {
  saveVisible.value = true
}

const confirmSave = () => {
  if (!saveForm.name) {
    ElMessage.warning('请输入配置名称')
    return
  }

  const config = {
    name: saveForm.name,
    description: saveForm.description,
    dataPermission: saveForm.dataPermission,
    fields: formFields.value,
    tableFields: formFields.value.filter(field => field.showInTable)
  }

  emit('save', config)
  saveVisible.value = false
  ElMessage.success('配置保存成功')
}

const handleClear = () => {
  formFields.value = []
  selectedFieldIndex.value = -1
  syncFormConfig()
}

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  if (newValue && Array.isArray(newValue)) {
    formFields.value = newValue
  } else {
    formFields.value = []
  }
}, { deep: true })

watch(() => props.configName, (newValue) => {
  if (newValue) {
    saveForm.name = newValue
  }
})
</script>

<style scoped>
.table-form-designer {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.designer-container {
  display: flex;
  flex: 1;
  height: 100%;
}

.component-panel {
  width: 250px;
  border-right: 1px solid #e4e7ed;
  background: #f8f9fa;
}

.panel-header {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.panel-header h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
}

.component-group {
  margin-bottom: 16px;
}

.component-group h4 {
  margin: 0 0 8px 0;
  padding: 8px 16px;
  font-size: 12px;
  color: #909399;
  background: #f0f0f0;
}

.component-items {
  padding: 0 8px;
}

.component-item {
  display: flex;
  align-items: center;
  padding: 8px;
  margin-bottom: 4px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: grab;
  background: white;
  transition: all 0.2s;
}

.component-item:hover {
  border-color: #409eff;
  background: #ecf5ff;
}

.component-item:active {
  cursor: grabbing;
}

.component-icon {
  margin-right: 8px;
  color: #409eff;
}

.component-name {
  font-size: 12px;
}

.design-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.design-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.design-header h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
}

.form-canvas {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.empty-canvas {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  border: 2px dashed #e4e7ed;
  border-radius: 8px;
  color: #909399;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.form-fields-list {
  min-height: 200px;
}

.form-field-wrapper {
  position: relative;
  margin-bottom: 16px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.form-field-wrapper:hover {
  border-color: #409eff;
}

.form-field-wrapper.active {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.field-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  display: none;
}

.form-field-wrapper:hover .field-actions,
.form-field-wrapper.active .field-actions {
  display: block;
}

.property-panel {
  width: 300px;
  border-left: 1px solid #e4e7ed;
  background: #f8f9fa;
}

.property-form {
  padding: 16px;
}

.no-selection {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;
}

.no-selection-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.options-config {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 8px;
}

.option-item {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
  align-items: center;
}

.option-item:last-child {
  margin-bottom: 0;
}
</style>